from threading import Thread
import Image, ImageFilter, ImageOps, ImageEnhance
from common import imageops
from StringIO import StringIO
from scavenger import Scavenger

class PreviewWorker(Thread):
    def __init__(self, op, args, editor):
        Thread.__init__(self)
        self.op = op
        self.args = args
        self.image = editor.view_image
        self.callback = editor.view_update_callback
        
    def run(self):
        # Create an in-memory version of the image.
        sio = StringIO()
        self.image.save(sio, 'JPEG', quality=95)
        image_data = sio.getvalue()
        
        try:
            if self.op == 'sharpen':
                data_handle = imageops.sharpen(image_data)
                image_data = Scavenger.fetch_data(data_handle)
                sio = StringIO(image_data)
                new_image = Image.open(sio)
            elif self.op == 'blur':
                data_handle = imageops.blur(image_data)
                image_data = Scavenger.fetch_data(data_handle)
                sio = StringIO(image_data)
                new_image = Image.open(sio)
            elif self.op == 'color':
                data_handle = imageops.color(image_data, self.args)
                image_data = Scavenger.fetch_data(data_handle)
                sio = StringIO(image_data)
                new_image = Image.open(sio)
            elif self.op == 'brightness':
                data_handle = imageops.brightness(image_data, self.args)
                image_data = Scavenger.fetch_data(data_handle)
                sio = StringIO(image_data)
                new_image = Image.open(sio)
            elif self.op == 'contrast':
                data_handle = imageops.contrast(image_data, self.args)
                image_data = Scavenger.fetch_data(data_handle)
                sio = StringIO(image_data)
                new_image = Image.open(sio)
            elif self.op == 'invert':
                data_handle = imageops.invert(image_data)
                image_data = Scavenger.fetch_data(data_handle)
                sio = StringIO(image_data)
                new_image = Image.open(sio)
            else:
                raise Exception('Unknown operation "%s".'%self.op)
            self.callback(True, new_image)
        except Exception, e:
            print e
            self.callback(False, e)
    